package org.xawl.news.servlet.login;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.xawl.news.dao.impl.role.RoleDaoImpl;
import org.xawl.news.dao.impl.user.UserDaoImpl;
import org.xawl.news.dao.role.RoleDao;
import org.xawl.news.dao.user.UserDao;
import org.xawl.news.entity.role.Role;
import org.xawl.news.entity.user.User;
import org.xawl.news.servlet.base.BaseServlet;
import org.xawl.news.util.AjaxJson;
import org.xawl.news.util.ImageCode;
import org.xawl.news.util.MD5Util;
import org.xawl.news.util.SessionUtil;
import org.xawl.news.util.StringUtil;

import com.alibaba.fastjson.JSON;

public class LoginServlet extends BaseServlet {

	private static final long serialVersionUID = 1L;
	
	private UserDao userDao = new UserDaoImpl();
	private RoleDao roleDao = new RoleDaoImpl();

	protected String login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		User currentUser = (User)SessionUtil.getCurrentUser(request);
		if (currentUser != null) {
			return "redirect:indexServlet?method=index";
		} else {
			Cookie[] cookies = ((HttpServletRequest) request).getCookies();
			String usernamecookie = null;
			String passwordcookie = null;
			if (cookies != null) {
				for (Cookie cookie : cookies) {
					if (cookie.getName().equals("usernamecookie")) {
						usernamecookie = URLDecoder.decode(cookie.getValue(), "UTF-8");
					}
					if (cookie.getName().equals("passwordcookie")) {
						passwordcookie = URLDecoder.decode(cookie.getValue(), "UTF-8");
					}
				}
				if (StringUtil.isNotEmpty(usernamecookie) && StringUtil.isNotEmpty(passwordcookie)) {
					User user = userDao.findByUsernameAndPwd(usernamecookie, passwordcookie);
					if (user != null) {
						if(StringUtil.isNotEmpty(user.getRoleId())) {
							Role role = roleDao.findById(user.getRoleId());
							SessionUtil.setCurrentRole(request, role);
						}
						SessionUtil.setCurrentUser(request, user);
						return "redirect:indexServlet?method=index";
					}
				} 
			}
			return "forward:system/login/login";
		}
		
	}
	
	protected void index(HttpServletRequest request, HttpServletResponse response) throws IOException  {
		AjaxJson j = new AjaxJson();
		PrintWriter out = response.getWriter();
		String username = request.getParameter("username");
		String password = MD5Util.MD5Encode(request.getParameter("password"), "UTF-8").toUpperCase();
		String vcode = request.getParameter("vcode");
		String code = SessionUtil.getCurrentImageCode(request);
		String online = request.getParameter("online");
		if (!code.equalsIgnoreCase(vcode)) {
			j.setSuccess(false);
			j.setMsg("验证码有误,请重新输入!");
		} else {
			User user = userDao.findByUsernameAndPwd(username, password);
			if (StringUtil.isNotEmpty(user)) {
				if (StringUtil.isNotEmpty(online) && online.equals("on")) {
					// 保存Cookie
					Cookie usernamecookie = new Cookie("usernamecookie", URLEncoder.encode(username, "UTF-8"));
					Cookie passwordcookie = new Cookie("passwordcookie", URLEncoder.encode(password, "UTF-8"));
					usernamecookie.setMaxAge(12 * 60 * 60);
					passwordcookie.setMaxAge(12 * 60 * 60);
					usernamecookie.setPath("/");
					passwordcookie.setPath("/");
					response.addCookie(usernamecookie);
					response.addCookie(passwordcookie);
				}
				if(StringUtil.isNotEmpty(user.getRoleId())) {
					Role role = roleDao.findById(user.getRoleId());
					SessionUtil.setCurrentRole(request, role);
				}
				SessionUtil.setCurrentUser(request, user);
				j.setMsg("登录成功，正在重定向...");
				j.setSuccess(true);
			} else {
				j.setMsg("用户名密码不匹配，请重新登录!");
				j.setSuccess(false);
			}
		}
		out.write(JSON.toJSONString(j));
	}
	
	
	/**
	 * @Title: save
	 * @Description: 默认方便初始化admin用户
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException String
	 * @throws @time 下午11:21:59
	 */
	protected void save(HttpServletRequest request, HttpServletResponse response) {
		Date currentTime = new Date();
		User user = new User();
		user.setUsername("zhangsan");
		user.setPassword(MD5Util.MD5Encode("123", "UTF-8").toUpperCase());
		user.setGender(0);
		user.setIsEnabled(0);
		user.setEmail("313355817@qq.com");
		user.setLastTime(currentTime);
		user.setCreateTime(currentTime);
		user.setUpdateTime(currentTime);
		userDao.save(user);
	}
	
	protected void code(HttpServletRequest request, HttpServletResponse response) {
		// 设置响应的类型格式为图片格式
		response.setContentType("image/jpeg");
		// 禁止图像缓存。
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		ImageCode vCode = new ImageCode(100, 40, 4, 10);
		SessionUtil.setCurrentImageCode(request,  vCode.getCode());
		try {
			vCode.write(response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	
	/**
	 * 
	 * @Title: logout 
	 * @Description: 退出(只移除session)
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 * @return: String
	 */
	protected String logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		SessionUtil.setCurrentUser(request, null);
		//销毁cookie
		Cookie[] cookies = request.getCookies();
		if(cookies != null) {
			for(Cookie cookie : cookies){
		        if(cookie.getName().equals("accountcookie")){
		        	cookie.setMaxAge(0);
		        	cookie.setPath("/");
		        	response.addCookie(cookie);
		        }
		        if(cookie.getName().equals("passwordcookie")){
		        	cookie.setMaxAge(0);
		        	cookie.setPath("/");
		        	response.addCookie(cookie);
		        }
		    }
		}
		return "redirect:login.jsp";
	}
	
	/**
	 * 
	 * @Title: exit 
	 * @Description: 切换账号(移除session,清除cookie)
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 * @return: String
	 */
	protected String exit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		SessionUtil.setCurrentUser(request, null);
		//销毁cookie
		Cookie[] cookies = request.getCookies();
		if(cookies != null) {
			for(Cookie cookie : cookies){
		        if(cookie.getName().equals("usernamecookie")){
		        	cookie.setMaxAge(0);
		        	cookie.setPath("/");
		        	response.addCookie(cookie);
		        }
		        if(cookie.getName().equals("passwordcookie")){
		        	cookie.setMaxAge(0);
		        	cookie.setPath("/");
		        	response.addCookie(cookie);
		        }
		    }
		}
		Cookie usernamecookie = new Cookie("usernamecookie",null);
		Cookie passwordcookie = new Cookie("passwordcookie",null);
		usernamecookie.setMaxAge(0);
		passwordcookie.setMaxAge(0);
		usernamecookie.setPath("/"); 
		passwordcookie.setPath("/"); 
	    response.addCookie(usernamecookie); 
	    response.addCookie(passwordcookie);
	    return "redirect:login.jsp";
	}
	

}
